/*
 *所有关于Aps_MachineCalendar类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Aps_MachineCalendarService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using DGZImp.ApsProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using DGZImp.ApsProject.IRepositories;
using DGZImp.ApsProject.Dtos;
using DGZImp.Core.DbSqlSugar;
using SqlSugar;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.Exceptions;
using DGZImp.BasProject.DomainModels;
using Microsoft.VisualBasic;

namespace DGZImp.ApsProject.Services
{
    public partial class Aps_MachineCalendarService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IAps_MachineCalendarRepository _repository;//访问数据库
        //public ServiceDbContext Db = AutofacContainerModule.GetService<ServiceDbContext>();


        [ActivatorUtilitiesConstructor]
        public Aps_MachineCalendarService(
            IAps_MachineCalendarRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public async Task<string> GenerateMachineCalendarData(ReqApsMathineCalendarInfo calendarInfo)
        {
            var calendarEntries = new List<Aps_MachineCalendar>();


            DateTime StartTime = Convert.ToDateTime(calendarInfo.StartTime);
            DateTime EndTime = Convert.ToDateTime(calendarInfo.EndTime);


            // 先删除之前的
            await _repository.SqlSugarClient.Deleteable<Aps_MachineCalendar>()
                              .Where(x => x.WorkDate >= StartTime && x.WorkDate <= EndTime)
                              .ExecuteCommandAsync();

            for (var date = StartTime; date <= EndTime; date = date.AddDays(1))
            {

                if (calendarInfo.Items != null)
                {

                    foreach (var i in calendarInfo.Items)
                    {
                        DateTime itemStartTime = Convert.ToDateTime(i.StartTime);
                        DateTime itemEndTime = Convert.ToDateTime(i.EndTime);

                        if (itemStartTime <= date.AddDays(1) && itemEndTime >= date)
                        {

                            var cStart = itemStartTime >= date ? itemStartTime : date;
                            var cEnd = itemEndTime < date.AddDays(1) ? itemEndTime : date.AddDays(1);
                            var entry1 = new Aps_MachineCalendar
                            {
                                WorkDate = date,
                                MachineId = i.MachineId,
                                StartTime = cStart,
                                EndTime = cEnd,
                                CalendarType = i.CalendarType,
                                // 计算EndTime和StartTime 时间差
                                Hours = (cEnd - cStart).TotalMinutes.ToString(),

                            };

                            calendarEntries.Add(entry1);
                        }
                        else
                        {
                            var entry2 = new Aps_MachineCalendar
                            {
                                WorkDate = date,
                                StartTime = null,
                                EndTime = null,

                            };
                            calendarEntries.Add(entry2);
                        }

                    }
                }
                else
                {
                    var entry = new Aps_MachineCalendar
                    {
                        WorkDate = date,
                        StartTime = null,
                        EndTime = null,

                    };
                    calendarEntries.Add(entry);
                }

            }


            await _repository.SqlSugarClient.DoInsertAsync<Aps_MachineCalendar>(calendarEntries);
            return "操作成功";
        }

        public async Task<List<ResLeanApsMachineCalendarInfo>> GetList(string time)
        {
            if (string.IsNullOrEmpty(time))
                throw new AppException("请选择年月");

            DateTime date = Convert.ToDateTime(time);
            DateTime begin = Convert.ToDateTime(date.Year + "-" + date.Month + "-01");
            DateTime end = begin.AddMonths(1).AddDays(-1);

            //var list = Db.Set<LeanBasePlantCalendar, LeanApsLineCalendar, LeanBaseForeman, LeanBaseSchedule>()
            var list = await _repository.SqlSugarClient.Set<Aps_MachineCalendar>()
                .LeftJoin<Bas_Machine>((a, b) => a.MachineId == b.MachineId && b.IsValid == 1)
                .OrderBy((a, b) => a.WorkDate)
                .Where((a, b) => a.WorkDate >= begin && a.WorkDate <= end)
                .Select((a, b) => new ResLeanApsMachineCalendarInfo
                {
                    MachineCalendarId = a.MachineCalendarId.SelectAll(),
                    MachineCode = b.MachineCode,
                    MachineName = b.MachineName

                }).ToListAsync();

            return list;
        }

        public async Task<string> UpdateMachine(UpdateApsMathineCalendarInfo UpdateInfo)
        {
            var info = _repository.SqlSugarClient.Set<Aps_MachineCalendar>().Where(a => a.MachineCalendarId == UpdateInfo.MachineCalendarId).FirstOrDefault();
            var calendarEntries = new List<Aps_MachineCalendar>();
            DateTime date = Convert.ToDateTime(UpdateInfo.Date);

            if (UpdateInfo.Items.Count > 0)
            {

                // 先删除之前的
                await _repository.SqlSugarClient.Deleteable<Aps_MachineCalendar>(a => a.WorkDate == date).ExecuteCommandAsync();

                foreach (var i in UpdateInfo.Items)
                {
                    TimeSpan Stime = TimeSpan.Parse(i.StartTime);
                    TimeSpan Etime = TimeSpan.Parse(i.EndTime);

                    // 将日期的时间部分替换为给定的时间
                    DateTime dateTimeS = new DateTime(date.Year, date.Month, date.Day, Stime.Hours, Stime.Minutes, 0);
                    DateTime dateTimeE = new DateTime(date.Year, date.Month, date.Day, Etime.Hours, Etime.Minutes, 0);

                    var entry = new Aps_MachineCalendar
                    {
                        WorkDate = date,
                        // 其他属性可以在这里初始化，例如：
                        MachineId = i.MachineId,
                        StartTime = dateTimeS,
                        EndTime = dateTimeE,
                        CalendarType = i.CalendarType,
                        Hours = i.Hours

                    };
                    calendarEntries.Add(entry);



                }
                await _repository.SqlSugarClient.DoInsertAsync(calendarEntries);
            }
            else
            {
                info.MachineId = null;
                info.StartTime = null;
                info.EndTime = null;
                _repository.SqlSugarClient.DoUpdate<Aps_MachineCalendar>(info, x => x.MachineCalendarId == UpdateInfo.MachineCalendarId);
            }


            return "修改成功";

        }

    }
}
